﻿using System;
using System.Web.Security;
using EzDesk.Core.Interface;
using EzDesk.Utility.Log;

namespace EzDesk.Core.ServiceImpl.Services
{
    public class AccountMembershipService : IMembershipService
    {
        private readonly MembershipProvider _provider;

        public MembershipProvider Provider
        {
            get { return _provider ?? Membership.Provider; }
        }

        public AccountMembershipService(MembershipProvider provider)
        {
            _provider = provider;

            //LogEx.TRACE("CoreService - AccountMembership", "初始化AccountMembership");
        }

        public int MinPasswordLength
        {
            get
            {
                return _provider.MinRequiredPasswordLength;
            }
        }

        public bool ValidateUser(string userName, string password)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");

            return _provider.ValidateUser(userName, password);
        }

        public MembershipCreateStatus CreateUser(string userName, string password)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");

            MembershipCreateStatus status;
            _provider.CreateUser(userName, password, "user@ezdesk.com", null, null, true, null, out status);
            return status;
        }

        public void ChangePassword(string userName, string oldPassword, string newPassword)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
            if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Value cannot be null or empty.", "newPassword");
            if (!_provider.ValidateUser(userName, oldPassword)) throw new ArgumentException("password is not right", "oldPassword");

            // The underlying ChangePassword() will throw an exception rather
            // than return false in certain failure scenarios.
            MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */);
            currentUser.ChangePassword(oldPassword, newPassword);
        }
    }
}